package cn.itcast.service.imp;

import cn.itcast.service.SearchService;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient client;
    @Override
    public List<Map> search(String search) throws IOException {
        List<Map> maps = searchResult(search);
        return maps;
    }
    private List<Map> searchResult(String search) throws IOException {
        //2.创建查询请求对象
        SearchRequest searchRequest = new SearchRequest("merchant");
//4. 创建查询条件构建器SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

//      构建高亮

        HighlightBuilder highlighter = new HighlightBuilder();
        highlighter.field("name");
        highlighter.field("address");
        highlighter.preTags("<em>");
        highlighter.postTags("</em>");
        sourceBuilder.highlighter(highlighter);

//    5.构建查询条件
        //1.构建boolQuery
        BoolQueryBuilder query = QueryBuilders.boolQuery();
//  6.查询构建
        QueryBuilder matchQuery = QueryBuilders.matchQuery("name", search);
        QueryBuilder matchQuery2 = QueryBuilders.matchQuery("address", search);
        query.should(matchQuery);
        query.should(matchQuery2);
//  7添加查询条件到构建起中
        sourceBuilder.query(query);
//3. 添加查询条件构建器 SearchSourceBuilder
//        排序规则
        GeoPoint geoPoint = new GeoPoint(30.7088, 104.046653);
        SortBuilder sortBuilder = new GeoDistanceSortBuilder("location", geoPoint);
        sourceBuilder.sort(sortBuilder);
        searchRequest.source(sourceBuilder);
//        查询结果：
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
//        获取命中对象
        SearchHits searcHits = response.getHits();
//        获取所有数据
        long value = searcHits.getTotalHits().value;
        System.out.println("总的命中数:"+value);
        List<Map> goodsList = new ArrayList<>();
        SearchHit[] hits = searcHits.getHits();
        for(SearchHit hit:hits){
            String sourceAsString = hit.getSourceAsString();
            Map map = JSON.parseObject(sourceAsString, Map.class);
            Object sortValue = hit.getSortValues()[0];
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField HighlightField = highlightFields.get("name");
            if(HighlightField!=null){
                Text[] fragments = HighlightField.fragments();
                map.put("name",fragments[0].toString());
            }
            HighlightField addressField = highlightFields.get("address");
            if(addressField!=null){
                Text[] addressFrament = addressField.fragments();
                map.put("address",addressFrament[0].toString());
                map.put("sort",sortValue);
            }
            goodsList.add(map);
        }
        return  goodsList;
    }
}
